<template>
  <div class="my-products-container">
    <div class="page-header">
      <h2>我的商品</h2>
      <div class="header-controls">
        <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange" style="width: 180px; margin-right: 16px;">
          <el-option label="发布时间（最新）" value="createTime-desc" />
          <el-option label="发布时间（最早）" value="createTime-asc" />
          <el-option label="价格（高到低）" value="price-desc" />
          <el-option label="价格（低到高）" value="price-asc" />
        </el-select>
        <el-button type="primary" @click="$router.push('/publish')">
          发布商品
        </el-button>
      </div>
    </div>
    
    <el-table
      v-loading="loading"
      :data="products"
      style="width: 100%"
    >
      <template #empty>
        <div class="empty-state">
          <el-icon size="64" color="#ccc"><Picture /></el-icon>
          <p>您还没有发布任何商品</p>
          <el-button type="primary" @click="$router.push('/publish')">
            立即发布商品
          </el-button>
        </div>
      </template>
      <el-table-column label="序号" width="80">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="商品图片" width="120">
        <template #default="{ row }">
          <el-image
            :src="getProductImage(row)"
            style="width: 80px; height: 80px"
            fit="cover"
          >
            <template #error>
              <div style="width: 80px; height: 80px; background: #f5f5f5; display: flex; align-items: center; justify-content: center; color: #ccc;">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>
              <el-table-column prop="inventory" label="库存" width="80" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <div class="status-tags">
            <el-tag v-if="row.isBargain" type="warning" size="small" style="margin-right: 5px;">
              可砍价
            </el-tag>
            <el-tag v-if="row.oldLevel" type="info" size="small">
              {{ getOldLevelText(row.oldLevel) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="发布时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleView(row)">
            查看
          </el-button>
          <el-button size="small" type="warning" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!-- 商品详情模态框 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="商品详情"
    width="800px"
    :before-close="handleCloseDetailDialog"
  >
    <div v-if="selectedProduct" class="product-detail-modal">
      <div class="product-images">
        <el-image
          :src="getProductImage(selectedProduct)"
          fit="cover"
          class="main-image"
          :preview-src-list="getProductImages(selectedProduct)"
        />
      </div>
      
      <div class="product-info-detail">
        <h2 class="product-title">{{ selectedProduct.name }}</h2>
        
        <div class="product-meta">
          <div class="meta-item">
            <span class="label">价格：</span>
            <span class="value price">¥{{ selectedProduct.price }}</span>
          </div>
          <div class="meta-item">
            <span class="label">库存：</span>
            <span class="value">{{ selectedProduct.inventory }}件</span>
          </div>
          <div class="meta-item">
            <span class="label">成色：</span>
            <span class="value">{{ getOldLevelText(selectedProduct.oldLevel) }}</span>
          </div>
          <div class="meta-item">
            <span class="label">可砍价：</span>
            <span class="value">
              <el-tag :type="selectedProduct.isBargain ? 'success' : 'info'" size="small">
                {{ selectedProduct.isBargain ? '是' : '否' }}
              </el-tag>
            </span>
          </div>
        </div>
        
        <div class="product-description">
          <h3>商品描述</h3>
          <p>{{ selectedProduct.detail || '暂无描述' }}</p>
        </div>
        
        <div class="product-time">
          <p>发布时间：{{ formatTime(selectedProduct.createTime) }}</p>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseDetailDialog">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOldLevelText } from '@/utils/product'
import { Picture } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { useProductStore } from '@/stores/product'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const productStore = useProductStore()
const userStore = useUserStore()

const products = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 排序相关
const sortBy = ref('createTime-desc') // 默认按发布时间倒序

// 模态框相关
const detailDialogVisible = ref(false)
const selectedProduct = ref<any>(null)

const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取商品图片
const getProductImage = (product: any) => {
  if (product.coverList && product.coverList.length > 0) {
    // 如果coverList是字符串，尝试解析为数组
    if (typeof product.coverList === 'string') {
      try {
        const images = JSON.parse(product.coverList)
        return images[0] || '/placeholder.svg'
      } catch (e) {
        return product.coverList
      }
    }
    // 如果已经是数组
    return product.coverList[0] || '/placeholder.svg'
  }
  return '/placeholder.svg'
}

// 获取商品图片列表（用于预览）
const getProductImages = (product: any) => {
  if (product.coverList) {
    if (typeof product.coverList === 'string') {
      try {
        const images = JSON.parse(product.coverList)
        return images && images.length > 0 ? images : ['/placeholder.svg']
      } catch (e) {
        return [product.coverList]
      }
    } else if (Array.isArray(product.coverList)) {
      return product.coverList.length > 0 ? product.coverList : ['/placeholder.svg']
    }
  }
  return ['/placeholder.svg']
}

const getStatusType = (status: number) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '下架'
    case 1: return '上架'
    case 2: return '已售'
    default: return '未知'
  }
}

const handleSortChange = (value: string) => {
  sortBy.value = value
  currentPage.value = 1 // 排序变化时重置到第一页
  loadMyProducts()
}

const loadMyProducts = async () => {
  try {
    loading.value = true
    
    // 检查用户是否已登录
    if (!userStore.user || !userStore.user.username) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    const result = await productStore.getMyProducts({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      userName: userStore.user.username,
      sortBy: sortBy.value // 使用sortBy变量
    })
    products.value = result.list
    total.value = result.total
  } catch (error: any) {
    console.error('获取我的商品失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const handleView = (product: any) => {
  selectedProduct.value = product
  detailDialogVisible.value = true
}

const handleCloseDetailDialog = () => {
  detailDialogVisible.value = false
  selectedProduct.value = null
}

const handleEdit = (product: any) => {
  router.push(`/edit/${product.id}`)
}

const handleDelete = async (product: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品"${product.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 调用删除商品API
    await productStore.deleteProduct(product.id)
    ElMessage.success('删除成功')
    loadMyProducts()
    
    // 通知父组件刷新统计数据
    const parentComponent = getCurrentInstance()?.parent
    if (parentComponent && parentComponent.exposed?.refreshStats) {
      parentComponent.exposed.refreshStats()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadMyProducts()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadMyProducts()
}

onMounted(() => {
  loadMyProducts()
})
</script>

<style scoped lang="scss">
.my-products-container {
  background: #fff;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    
    h2 {
      margin: 0;
      color: #2c3e50;
      font-size: 24px;
      font-weight: 600;
      position: relative;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 0;
        width: 40px;
        height: 3px;
        background: linear-gradient(90deg, #ff6b35, #f7931e);
        border-radius: 2px;
      }
    }
    
    .header-controls {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }
}

.status-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.pagination-wrapper {
  margin-top: 30px;
  text-align: center;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-table__header {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  }
  
  .el-table__row:hover {
    background-color: #f8f9fa;
  }
}

:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  
  p {
    margin: 20px 0;
    font-size: 16px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-products-container {
    padding: 20px;
    
    .page-header {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start;
      
      h2 {
        font-size: 20px;
      }
      
      .header-controls {
        width: 100%;
        justify-content: space-between;
        
        .el-select {
          width: 140px;
          margin-right: 0;
        }
      }
    }
  }
  
  :deep(.el-table) {
    font-size: 14px;
  }
  
  :deep(.el-button) {
    font-size: 12px;
    padding: 6px 12px;
  }
}

/* 商品详情模态框样式 */
.product-detail-modal {
  display: flex;
  gap: 24px;
}

.product-images {
  flex: 0 0 300px;
}

.main-image {
  width: 100%;
  height: 300px;
  border-radius: 8px;
  object-fit: cover;
}

.product-info-detail {
  flex: 1;
}

.product-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 16px;
}

.product-meta {
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  
  .label {
    font-weight: 500;
    color: #666;
    min-width: 80px;
  }
  
  .value {
    color: #2c3e50;
    
    &.price {
      color: #e74c3c;
      font-size: 18px;
      font-weight: 600;
    }
  }
}

.product-description,
.product-time {
  margin-bottom: 20px;
  
  h3 {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
    margin: 0 0 8px;
  }
  
  p {
    color: #666;
    line-height: 1.6;
    margin: 0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-detail-modal {
    flex-direction: column;
    gap: 16px;
  }
  
  .product-images {
    flex: none;
  }
  
  .main-image {
    height: 200px;
  }
}
</style> 